package mall

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"mall-go/common"
	"mall-go/dto"
	"mall-go/model"
	"mall-go/repository"
	"mall-go/response"
	"strconv"
)

type MallOrderController struct {
	DB *gorm.DB
}

func NewMallOrderController() MallOrderController {
	db := common.GetDB()
	db.AutoMigrate(model.Order{})
	return MallOrderController{DB: db}
}

// SaveOrder 生成订单接口
//todo 这里应该开启事务
func (receiver MallOrderController) SaveOrder(ctx *gin.Context) {
	orderRepo := repository.NewMallOrderRepo()
	var request dto.OrderRequest
	ctx.Bind(&request)
	user, _ := ctx.Get("mallUser")
	userId := user.(model.MallUser).UserID

	priceTotal := 0
	if request.AddressId == 0 || len(request.CartItemIds) == 0 {
		panic("参数错误！")
	}
	itemsForSave := orderRepo.GetCartItemsForSettle(request.CartItemIds, userId)
	if len(itemsForSave) == 0 {
		panic("参数异常")
	}
	//总价
	for _, vo := range itemsForSave {
		priceTotal += vo.GoodsCount * vo.SellingPrice
	}
	if priceTotal < 1 {
		panic("价格异常")
	}
	userAddress := orderRepo.GetMallUserAddressById(request.AddressId)
	//检验是否为本用户
	if userId != userAddress.UserID {
		panic("非法操作")
	}
	//保存订单并返回订单号
	saveOrderResult := orderRepo.SaveOrder(userId, userAddress, itemsForSave)
	response.Success(ctx, gin.H{"saveOrderResult": saveOrderResult}, "Success")
}

// OrderDetailPage 订单详情接口
func (receiver MallOrderController) OrderDetailPage(ctx *gin.Context) {
	orderRepo := repository.NewMallOrderRepo()
	orderNo := ctx.Params.ByName("orderNo")
	user, _ := ctx.Get("mallUser")
	userId := user.(model.MallUser).UserID
	orderDetailVO := orderRepo.GetOrderDetailByOrderNo(orderNo, userId)
	response.Success(ctx, gin.H{"orderDetailVO": orderDetailVO}, "Success")
}

// OrderList 订单列表接口
//todo 这个接口有问题！！！
func (receiver MallOrderController) OrderList(ctx *gin.Context) {
	//todo 这里有坑，因为如果不传status 默认会给0，但是0有特殊意义
	user, _ := ctx.Get("mallUser")
	userId := user.(model.MallUser).UserID
	pageNumber, _ := strconv.Atoi(ctx.Query("pageNumber"))
	status, _ := strconv.Atoi(ctx.Query("status"))

	orderDTO := dto.OrderPageDTO{
		UserId:      userId,
		Page:        pageNumber,
		Limit:       5,
		OrderStatus: status,
		Start:       (pageNumber - 1) * 5,
	}
	orderRepo := repository.NewMallOrderRepo()
	orders := orderRepo.GetMyOrders(orderDTO)
	response.Success(ctx, gin.H{"orders": orders}, "Success")
}

// CancelOrder 取消订单
func (receiver MallOrderController) CancelOrder(ctx *gin.Context) {
	orderNo := ctx.Params.ByName("orderNo")
	user, _ := ctx.Get("mallUser")
	userId := user.(model.MallUser).UserID
	orderRepo := repository.NewMallOrderRepo()

	cancelOrderResult := orderRepo.CancelOrder(orderNo, userId)
	if cancelOrderResult == "Success" {
		response.Success(ctx, nil, cancelOrderResult)
	} else {
		response.Failure(ctx, nil, cancelOrderResult)
	}
}

// FinishOrder 确认订单
func (receiver MallOrderController) FinishOrder(ctx *gin.Context) {
	orderNo := ctx.Params.ByName("orderNo")
	user, _ := ctx.Get("mallUser")
	userId := user.(model.MallUser).UserID
	orderRepo := repository.NewMallOrderRepo()

	finishOrderResult := orderRepo.FinishOrder(orderNo, userId)
	if finishOrderResult == "Success" {
		response.Success(ctx, nil, finishOrderResult)
	} else {
		response.Failure(ctx, nil, finishOrderResult)
	}
}

// PaySuccess 模拟支付成功回调的接口
// todo 具体的 后续可以接 沙箱环境 来模拟真实情况
func (receiver MallOrderController) PaySuccess(ctx *gin.Context) {
	orderRepo := repository.NewMallOrderRepo()
	orderNo := ctx.Query("orderNo")
	//使用json包处理
	orderNoMap := make(map[string]string)
	json.Unmarshal([]byte(orderNo), &orderNoMap)
	orderNo = orderNoMap["saveOrderResult"]
	payType, _ := strconv.Atoi(ctx.Query("payType"))
	payResult := orderRepo.PaySuccess(orderNo, payType)
	if payResult == "Success" {
		response.Success(ctx, nil, payResult)
	} else {
		response.Failure(ctx, nil, payResult)
	}
}
